<template>
  <div class="community-manage">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>社区管理</span>
          <div class="header-right">
            <el-input
              v-model="searchQuery"
              placeholder="搜索帖子"
              style="width: 200px; margin-right: 10px"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
            <el-select v-model="selectedTag" clearable placeholder="按标签筛选" style="width: 150px; margin-right: 10px">
              <el-option
                v-for="tag in tags"
                :key="tag.id"
                :label="tag.name"
                :value="tag.id"
              />
            </el-select>
          </div>
        </div>
      </template>

      <!-- 帖子列表 -->
      <el-table
        v-loading="loading"
        :data="postList"
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="作者信息" width="200">
          <template #default="{ row }">
            <div class="user-info">
              <el-avatar :size="32" :src="row.userAvatar">
                {{ row.userNickname?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <span class="user-nickname">{{ row.userNickname }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="200">
          <template #default="{ row }">
            <el-button type="primary" link @click="showPostDetail(row.id)">
              {{ row.title }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="统计信息" width="200">
          <template #default="{ row }">
            <div class="post-stats">
              <el-tooltip content="浏览量">
                <span><el-icon><View /></el-icon> {{ row.viewCount }}</span>
              </el-tooltip>
              <el-tooltip content="点赞数">
                <span><el-icon><Star /></el-icon> {{ row.likeCount }}</span>
              </el-tooltip>
              <el-tooltip content="评论数">
                <span><el-icon><ChatLineRound /></el-icon> {{ row.commentCount }}</span>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="发布时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="showPostDetail(row.id)">
              查看
            </el-button>
            <el-button 
              type="danger" 
              link 
              @click="handleDelete(row.id)"
              :disabled="row.status === 2"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="帖子详情"
      width="800px"
      destroy-on-close
    >
      <div v-loading="detailLoading" class="post-detail">
        <template v-if="currentPost">
          <div class="post-header">
            <div class="user-info">
              <el-avatar :size="40" :src="currentPost.userAvatar">
                {{ currentPost.userNickname?.charAt(0)?.toUpperCase() }}
              </el-avatar>
              <div class="user-meta">
                <div class="user-nickname">{{ currentPost.userNickname }}</div>
                <div class="post-time">{{ formatDateTime(currentPost.createTime) }}</div>
              </div>
            </div>
            <div class="post-status">
              <el-tag :type="getStatusType(currentPost.status)">
                {{ getStatusText(currentPost.status) }}
              </el-tag>
            </div>
          </div>
          
          <h2 class="post-title">{{ currentPost.title }}</h2>
          
          <div class="post-content" v-html="currentPost.content"></div>
          
          <!-- 图片展示 -->
          <div v-if="currentPost.images && currentPost.images.length > 0" class="post-images">
            <el-image
              v-for="(image, index) in currentPost.images"
              :key="index"
              :src="image"
              :preview-src-list="currentPost.images"
              fit="cover"
              class="post-image"
            />
          </div>

          <div class="post-footer">
            <div class="post-stats">
              <span><el-icon><View /></el-icon> {{ currentPost.viewCount }} 浏览</span>
              <span>
                <el-icon><Star /></el-icon> 
                {{ currentPost.likeCount }} 点赞
                <el-tag v-if="currentPost.isLiked" size="small" type="danger">已点赞</el-tag>
              </span>
              <span>
                <el-icon><Star /></el-icon> 
                {{ currentPost.commentCount }} 评论
              </span>
              <span>
                <el-icon><Collection /></el-icon>
                <el-tag v-if="currentPost.isFavorited" size="small" type="warning">已收藏</el-tag>
              </span>
            </div>
            <div class="post-meta">
              <div>创建时间：{{ formatDateTime(currentPost.createTime) }}</div>
              <div>更新时间：{{ formatDateTime(currentPost.updateTime) }}</div>
            </div>
          </div>
        </template>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, View, Star, ChatLineRound, Collection } from '@element-plus/icons-vue'
import { getPostList, getPostDetail, deletePost, getAllTags, getPostsByTag } from '@/api/community'

// 数据
const loading = ref(false)
const detailLoading = ref(false)
const postList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const searchQuery = ref('')
const selectedTag = ref('')
const tags = ref([])
const dialogVisible = ref(false)
const currentPost = ref(null)

// 获取帖子列表
const fetchPosts = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value
    }
    
    let response
    if (selectedTag.value) {
      response = await getPostsByTag(selectedTag.value, params)
    } else {
      response = await getPostList(params)
    }
    
    if (response.code === 200) {
      // 添加日期调试信息
      console.log('Post data:', response.data.records)
      postList.value = response.data.records
      total.value = response.data.total
    }
  } catch (error) {
    console.error('获取帖子列表失败:', error)
    ElMessage.error('获取帖子列表失败')
  } finally {
    loading.value = false
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const response = await getAllTags()
    if (response.code === 200) {
      tags.value = response.data
    }
  } catch (error) {
    console.error('获取标签列表失败:', error)
    ElMessage.error('获取标签列表失败')
  }
}

// 查看帖子详情
const showPostDetail = async (id) => {
  dialogVisible.value = true
  detailLoading.value = true
  try {
    const response = await getPostDetail(id)
    if (response.code === 200) {
      currentPost.value = response.data
    }
  } catch (error) {
    console.error('获取帖子详情失败:', error)
    ElMessage.error('获取帖子详情失败')
  } finally {
    detailLoading.value = false
  }
}

// 删除帖子
const handleDelete = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这篇帖子吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await deletePost(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      fetchPosts()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除帖子失败:', error)
      ElMessage.error('删除帖子失败')
    }
  }
}

// 获取状态类型
const getStatusType = (status) => {
  switch (status) {
    case 0: return 'info'    // 草稿
    case 1: return 'success' // 已发布
    case 2: return 'danger'  // 已删除
    default: return 'info'
  }
}

// 获取状态文本
const getStatusText = (status) => {
  switch (status) {
    case 0: return '草稿'
    case 1: return '已发布'
    case 2: return '已删除'
    default: return '未知'
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPosts()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPosts()
}

// 搜索处理
const handleSearch = () => {
  currentPage.value = 1
  fetchPosts()
}

// 监听标签选择变化
watch(selectedTag, () => {
  currentPage.value = 1
  fetchPosts()
})

// 格式化日期时间
const formatDateTime = (dateStr) => {
  if (!dateStr) return ''
  try {
    // 处理数组格式的时间 [year, month, day, hour, minute, second]
    if (Array.isArray(dateStr)) {
      const [year, month, day, hour, minute, second] = dateStr
      return `${year}年${String(month).padStart(2, '0')}月${String(day).padStart(2, '0')}日 ${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}:${String(second).padStart(2, '0')}`
    }
    
    // 处理字符串格式的时间
    if (typeof dateStr === 'string') {
      const date = new Date(dateStr)
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        })
      }
    }
    
    return dateStr
  } catch (error) {
    console.error('日期格式化错误:', error, dateStr)
    return dateStr
  }
}

// 初始化
onMounted(() => {
  fetchPosts()
  fetchTags()
})
</script>

<style scoped>
.community-manage {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-right {
  display: flex;
  align-items: center;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-nickname {
  font-weight: 500;
}

.post-stats {
  display: flex;
  gap: 15px;
}

.post-stats span {
  display: flex;
  align-items: center;
  gap: 5px;
  color: #666;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.post-detail {
  padding: 20px;
}

.post-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.user-meta {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.post-time {
  font-size: 12px;
  color: #999;
}

.post-title {
  margin: 20px 0;
  font-size: 24px;
  font-weight: 600;
}

.post-content {
  margin: 20px 0;
  line-height: 1.6;
}

.post-images {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  gap: 10px;
  margin: 20px 0;
}

.post-image {
  width: 150px;
  height: 150px;
  border-radius: 4px;
  cursor: pointer;
}

.post-footer {
  margin-top: 20px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.post-meta {
  margin-top: 10px;
  font-size: 12px;
  color: #999;
}

:deep(.el-dialog__body) {
  padding: 0;
}
</style>
